package com.cgl.controller;

import com.cgl.pojo.Result;
import com.cgl.service.UserActionService;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.logging.Logger;

@RestController
public class UserActionCcontroller {
    @Autowired
    private UserActionService userActionService;
    private static final Logger logger = Logger.getLogger(UserActionCcontroller.class.getName());
    @GetMapping("userAction/addUserVisitAction")
    public Result addUserVisitAction(HttpServletRequest request){
        String ip = request.getRemoteAddr();
        ip = getIPv4Address(ip); // 转换为IPv4地址
        logger.info("ip:"+ip+"访问");
        int result = userActionService.addUserVisitAction(ip);
        if (result>0){
            return Result.success();
        }else {
            return Result.error("添加失败");
        }
    }
    private static String getIPv4Address(String ip) {
        // 如果是IPv6的本地回环地址，直接返回IPv4的本地回环地址
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            return "127.0.0.1";
        }
        // 如果是IPv6的映射IPv4地址，提取IPv4部分
        if (ip.contains(":")) {
            int ipv4PartIndex = ip.lastIndexOf(':');
            ip = ip.substring(ipv4PartIndex + 1);
        }
        return ip;
    }
    @GetMapping("userAction/getLastAllUserNumber")
    public Result getLastAllUserNumber(){
        logger.info("获取近7天的访问量");
        int[] result = userActionService.getLastAllUserNumber(7);
        return Result.success(result);
    }
}
